package sk.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import sk.model.Player;
import sk.model.Session;

public class Server {

	private static String dbHost = "46.163.107.25";
	private static String dbPort = "3306";
	private static String dbName = "schafkopf_ss13";
	private static String user = "skScoreAndroid";
	private static String passwd = "asdfasdf";

	private static Connection conn;

	public static Player[] getPlayerList() {
		if (connectDB()) {
			LinkedList<Player> player = new LinkedList<Player>();

			Statement stmt = null;
			ResultSet rs = null;
			try {
				stmt = conn.createStatement();
				rs =
					stmt.executeQuery("SELECT id, firstname, surname FROM player");
				while (rs.next()) {
					player.add(new Player(rs.getString(2), rs.getString(3), rs
						.getInt(1)));
				}
			} catch (SQLException ex) {
				// handle any errors
				System.out.println("SQLException: " + ex.getMessage());
				System.out.println("SQLState: " + ex.getSQLState());
				System.out.println("VendorError: " + ex.getErrorCode());
			} finally {
				if (rs != null) {
					try {
						rs.close();
					} catch (SQLException sqlEx) {
					} // ignore
					rs = null;
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlEx) {
				} // ignore
				stmt = null;
			}

			disconnectDB();
			// return (Player[]) player.toArray();
			return player.toArray(new Player[] {});
		}

		return null;
	}

	public static void sendSessions(List<Session> sessions) {

	}

	public static long getTime() {
		return System.currentTimeMillis();
	}

	private static boolean connectDB() {
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
		} catch (ClassNotFoundException cnfe) {
			System.out.println("Could not load database-driver: "
				+ cnfe.getMessage());
			return false;
		}

		try {
			conn =
				DriverManager.getConnection("jdbc:mysql://" + dbHost + ":"
					+ dbPort + "/" + dbName, user, passwd);
		} catch (SQLException sqle) {
			System.out.println("Connection failed: " + sqle.getMessage());
			return false;
		}

		return true;
	}

	private static void disconnectDB() {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException sqle) {
				System.out.println(sqle.getMessage());
			}
		}
	}
}
